//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Resource Application Block
//===============================================================================

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;
using EntLibContrib.Resource.Providers;

namespace EntLibContrib.Resource.Configuration.Design
{
	class ResourceManagerSettingsNodeBuilder : NodeBuilder
	{
		#region Fields
		private ResourceManagerSettings resourceManagerSettings;
		private ResourceManagerNode defaultNode;
		#endregion

		#region Construction
		public ResourceManagerSettingsNodeBuilder (IServiceProvider serviceProvider, ResourceManagerSettings resourceManagerSettings)	: base(serviceProvider)
		{
			this.resourceManagerSettings = resourceManagerSettings;
		}
		#endregion

		#region Public Methods
		public ResourceManagerSettingsNode Build ()
		{
			ResourceManagerSettingsNode rootNode = new ResourceManagerSettingsNode();
			ResourceManagerCollectionNode node = new ResourceManagerCollectionNode();
			foreach ( ResourceManagerData data in resourceManagerSettings.ResourceManagers )
			{
				CreateResourceManagerNode(node, data);
			}
			rootNode.AddNode(node);
			rootNode.DefaultResourceManager = defaultNode;
			rootNode.RequirePermission = resourceManagerSettings.SectionInformation.RequirePermission;
			return rootNode;
		}
		#endregion

		#region Private Methods
		private void CreateResourceManagerNode (ResourceManagerCollectionNode node, ResourceManagerData resourceManagerData)
		{
			ResourceManagerNode resourceManagerNode = new ResourceManagerNode(resourceManagerData);
			node.AddNode(resourceManagerNode);
			if ( resourceManagerNode.Name == resourceManagerSettings.DefaultResourceManager ) defaultNode = resourceManagerNode;
			CreateProviderNode(resourceManagerNode, resourceManagerData.ResourceProvider);
		}

		private void CreateProviderNode (ResourceManagerNode resourceManagerNode, string resourceProviderName)
		{
			if ( string.IsNullOrEmpty(resourceProviderName) ) return;

			ResourceProviderData resourceProviderData = resourceManagerSettings.ResourceProviders.Get(resourceProviderName);
			if ( null == resourceProviderData )
			{
				LogError(resourceManagerNode, string.Format(CultureInfo.CurrentUICulture, InternalResources.ExceptionNoResourceProviderDefined, resourceProviderName));
				return;
			}

			ConfigurationNode providerNode = NodeCreationService.CreateNodeByDataType(resourceProviderData.GetType(), new object[] { resourceProviderData });
			if ( null == providerNode )
			{
				LogNodeMapError(resourceManagerNode, resourceProviderData.GetType());
				return;
			}
			resourceManagerNode.AddNode(providerNode);
		}
		#endregion
	}
}